<?php

namespace App\Admin\Controllers\Collecter;

use App\Admin\Actions\Extensions\CollecterConfigButton;
use App\Admin\Actions\Extensions\ImportCollectJsonButton;
use App\Admin\Actions\Grid\BatchCollecterProcessAction;
use App\Admin\Actions\Grid\BatchCollecterpublishAction;
use App\Admin\Metrics\Collecter\collectedStatus;
use App\Models\Circle\WxCircle;
use App\Models\Collecter\MiniCollecterCollected;
use App\Models\User\WxUser;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Admin\Metrics\Users\RobotUsers;
use Illuminate\Support\Facades\DB;

class MiniCollecterCollectedController extends AdminController
{
    public function index(Content $content)
    {
        return $content
            ->header('收集数据')
            ->description('收集的数据在处理完成之后，你可以手动勾选发布，也可以等程序自动发布（10分站一次）')
            ->body(function (Row $row) {
                $row->column(6,new RobotUsers());
                $row->column(6,new collectedStatus());
            })
            ->body($this->grid());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new MiniCollecterCollected(), function (Grid $grid) {

            $counts = DB::table('wx_user')
                ->select(
                    DB::raw('SUM(CASE WHEN is_robot > 0 THEN 1 ELSE 0 END) AS robot_count'),
                    DB::raw('SUM(CASE WHEN is_robot = 1 THEN 1 ELSE 0 END) AS free_robot_count'),
                )->first();
            if($counts){
                if($counts->robot_count <= 0){
                    $grid->header(function ($collection) {
                        return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;display: inline-block;margin-top: 20px;">你还一个机器人都没有呢，无法做任何操作，先去<a href="'.admin_url('users').'">用户管理</a>添加机器人</div>';
                    });
                }else if($counts->free_robot_count <= 0){
                    $grid->header(function ($collection) {
                        return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;display: inline-block;margin-top: 20px;">可绑定的机器人不足，你可以去<a href="'.admin_url('users').'">用户管理</a>添加机器人， 默认一个机器人账号绑定一个第三方账号，你也可以设置一个机器人账号绑定多个第三方账号</div>';
                    });
                }
            }


            $grid->simplePaginate();
            $grid->quickSearch(['id', 'link','author','title', 'content'])->placeholder('搜索文章ID，标题，内容，作者...')->width(50);
            $grid->column('id')->sortable();
            $grid->model()->orderBy('id', 'desc');
//            $grid->column('post_unique');
//            $grid->column('author_unique');
            $grid->column('link')->display(function ($v){
                return '<a href="'.$v.'" target="_blank">查看</a>';
            });
            $grid->column('author');
            $grid->column('title_or_content', '预览')->display(function ($v){
                if($this->title){
                    return $this->title;
                }
                if($this->content){
                    return mb_substr(strip_tags($this->content), 0, 40) . '...';
                }
                return '';
            })->limit(20);
            $grid->column('imgs')->display(function ($v){
                return count(json_decode($v, true));
            });
            $grid->column('comments')->display(function ($v){
                if(is_string($v)){
                    $com_arr = json_decode($v, true);
                    if($com_arr && is_array($com_arr)){
                        return count($com_arr);
                    }
                }else if(is_array($v)){
                    return count($v);
                }

            });
            $grid->column('tags')->display(function ($v){
                return count(json_decode($v, true));
            });
            $grid->column('musics');
            $grid->column('videos')->display(function ($v){
                if(is_string($v)){
                    return count(json_decode($v, true));
                }else if(is_array($v)){
                    return count($v);
                }
                return 0;
            });
            $grid->column('post_id');
            $grid->column('status')->using([0 => '待处理', 1 => '待发布', 2 => '已发布', 3 => '处理中', 4 => '处理失败'])->label([
                0=>'red',
                1=>'green',
                2=>'default',
                3 => 'red',
                4 => 'darkred'
            ])->sortable();
            $grid->column('tenant_id')->editable();
//            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });

            $grid->tools([
                new CollecterConfigButton(),
                new ImportCollectJsonButton()
            ]);

            $grid->disableCreateButton();

            $grid->batchActions(function ($batch) {
                $batch->add((new BatchCollecterpublishAction()));
                $batch->add((new BatchCollecterProcessAction()));
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
//                $actions->append((new PostCommentLotteryAction())->setKey($this->id));
            });

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new MiniCollecterCollected(), function (Show $show) {
            $show->field('id');
            $show->field('post_unique');
            $show->field('author_unique');
            $show->field('link');
            $show->field('author');
            $show->field('title');
            $show->field('content');
            $show->field('imgs');
            $show->field('comments');
            $show->field('tags');
            $show->field('musics');
            $show->field('videos');
            $show->field('post_id');
            $show->field('circle_id');
            $show->field('user_id');
            $show->field('tenant_id');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new MiniCollecterCollected(), function (Form $form) {
            $form->display('id');
            $form->text('post_unique');
            $form->text('author_unique');
            $form->text('link');
            $form->text('author');
            $form->text('title');
            if(__system_is_model_enable('laradocs', 'dcat-neditor')){
                $form->neditor('content');
            }else{
                $form->editor('content');
            }
//            $form->text('imgs');
//            $form->text('comments');
//            $form->text('tags');
//            $form->text('musics');
//            $form->text('videos');
            $form->text('post_id');
            $form->select('circle_id', '发布圈子')->options(WxCircle::pluck('circle_name','id'));
            $form->select('user_id', '用户')->options(function ($id) {
                if($id){
                    $user = \App\Models\User\WxUser::find($id);
                    if ($user) {
                        return [$user->id => $user->user_name];
                    }
                }
            })->ajax('select/users');
//            $form->text('status');
            $form->text('tenant_id');
            $form->display('created_at');
            $form->display('updated_at');

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    return $form->response()->error('权限不足，不可以删除其他分站对象');
                }
            });

        });
    }
}
